package com.atguigu.crowd.handler;

import com.atguigu.crowd.api.MySQLRemoteService;
import com.atguigu.crowd.config.OSSProperties;
import com.atguigu.crowd.entity.vo.*;
import com.atguigu.crowd.util.CrowdConstant;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ProjectConsumerHandler {

    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;


    @RequestMapping("/get/detail/project/{projectId}")
    public String getProjectDetail(@PathVariable("projectId") Integer projectId, Model model){
        ResultEntity<DetailProjectVO> detailProjectRemote = mySQLRemoteService.getDetailProjectRemote(projectId);

        if (ResultEntity.SUCCESS.equals(detailProjectRemote.getResult())){
            DetailProjectVO detailProjectVO = detailProjectRemote.getData();

            model.addAttribute("detailProjectVO",detailProjectVO);
        }

        return "project-detail";
    }


    @RequestMapping("/create/confirm")
    public String saveConfirmString(HttpSession session, MemberConfirmInfoVO memberConfirmInfoVO,ModelMap modelMap){
        // 1.从 Session 域读取之前临时存储的 ProjectVO 对象
        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
        // 2.如果 projectVO 为 null
        if (projectVO == null) {
            throw new RuntimeException(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
        }

        // 3.将确认信息数据设置到 projectVO 对象中
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);

        // 4.从 Session 域读取当前登录的用户
        MemberLoginVO memberLoginVO = (MemberLoginVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        Integer memberId = memberLoginVO.getId();
        // 5.调用远程方法保存 projectVO 对象
        ResultEntity<String> saveResultEntity = mySQLRemoteService.saveProjectVORemote(projectVO,memberId);

        if (ResultEntity.ERROR.equals(saveResultEntity.getResult())){
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,saveResultEntity.getMessage());
            return "project-confirm";
        }

        session.removeAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
        return "redirect:/project/create/success";
    }

    @ResponseBody
    @RequestMapping("/create/save/return")
    public ResultEntity<String> saveReturn(ReturnVO returnVO ,HttpSession session) {

        try {
            // 从session中读取之前缓存的ProjectVO对象
            ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
            //判断projectVO是否为null
            if (projectVO == null) {
                return ResultEntity.errorData(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
            }

            List<ReturnVO> returnVOList = projectVO.getReturnVOList();

            // 判断returnVOList集合是否有效
            if (returnVOList == null || returnVOList.size() == 0) {
                returnVOList = new ArrayList<>();

                //为了让以后能够正常使用这个集合，设置到 projectVO 对象中
                projectVO.setReturnVOList(returnVOList);

            }
            returnVOList.add(returnVO);

            //把数据有变化的 ProjectVO 对象重新存入 Session 域，以确保新的数据最终能够存入 Redis
            session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT,projectVO);

            return ResultEntity.successData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.errorData(e.getMessage());
        }

    }

    @ResponseBody
    @RequestMapping("/create/upload/return/picture")
    public ResultEntity<String> uploadReturnPicture(@RequestParam("returnPicture") MultipartFile multipartFile) throws IOException {

        // 执行上传
        ResultEntity<String> returnPicture = CrowdUtil.uploadFileToOss(ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                multipartFile.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                multipartFile.getOriginalFilename());

        return returnPicture;
    }


    @RequestMapping("/create/project/information")
    public String saveProjectBasicInfo(
            //接收普通数据
            ProjectVO projectVO,
            //接收头图
            MultipartFile headerPicture,
            //接收详情图，多个
            List<MultipartFile> detailPictureList,

            HttpSession session,

            ModelMap modelMap) throws IOException {




        // 1.完成头图上传
        boolean headerPictureisEmpty = headerPicture.isEmpty();
        if (headerPictureisEmpty) {

            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_HEADER_PIC_EMPTY);
            return "project-launch";

        }
        // 2.执行上传流程
        ResultEntity<String> uploadFileToOssResultEntity = CrowdUtil.uploadFileToOss(
                ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                headerPicture.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                headerPicture.getOriginalFilename());

        String result = uploadFileToOssResultEntity.getResult();

        // 3.判断是否上传成功
        if(ResultEntity.SUCCESS.equals(result)){
            // 4.获取返回的图片访问地址
            String headerPicturePath = uploadFileToOssResultEntity.getData();
            projectVO.setHeaderPicturePath(headerPicturePath);
        }else{

            // 返回给前端信息
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_HEADER_PIC_UPLOAD_FAILED);
            return "project-launch";
        }

        //创建一个用来存放详情图的集合
        List<String> detailPicturePathList = new ArrayList<>();

        if (detailPictureList == null || detailPictureList.size() == 0){
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
            return "project-launch";
        }

        //5.遍历detailPictureList集合
        for (MultipartFile detailPicture : detailPictureList) {
            // 6.判断是否为空
            if (detailPicture.isEmpty()) {
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
                return "project-launch";
            }

            // 7.执行上传
            ResultEntity<String> detailUploadResultEntity = CrowdUtil.uploadFileToOss(
                    ossProperties.getEndPoint(),
                    ossProperties.getAccessKeyId(),
                    ossProperties.getAccessKeySecret(),
                    detailPicture.getInputStream(),
                    ossProperties.getBucketName(),
                    ossProperties.getBucketDomain(),
                    detailPicture.getOriginalFilename());



            // 成功就将图片路径add到detailPicturePathList
            if (ResultEntity.SUCCESS.equals(detailUploadResultEntity.getResult())){
                String detailPicturePath = detailUploadResultEntity.getData();
                detailPicturePathList.add(detailPicturePath);
                System.out.println(11);
            }else {
                //上传失败返回消息
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_DETAIL_PIC_UPLOAD_FAILED);
                return "project-launch";
            }
        }

        projectVO.setDetailPicturePathList(detailPicturePathList);

        //8. 将ProjectVO存入session域
        session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT,projectVO);

        return "redirect:/project/return/info/page";
    }
}
